<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .box {
        width: 100px;
        height: 2000px;
      }
      .search {
        width: 300px;
        height: 50px;
        background: cyan;
        position: absolute;
        left: 50%;
        transform: translate(-50%);
        top: 100px;
      }
      button {
        position: absolute;
        top: 2000px;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <button>点击回到顶部</button>
    <div class="search"></div>
    <script>
      //一.悬浮搜索框
      var searchEle = document.querySelector(".search");
      //1.监听浏览器滚动的事件
      window.onscroll = function () {
        //2.获取卷掉的高度
        var scrollNum = document.documentElement.scrollTop;
        // console.log(scrollNum);
        if (scrollNum >= 100) {
          searchEle.style.position = "fixed";
          searchEle.style.top = "0px";
        } else {
          searchEle.style.position = "absolute";
          searchEle.style.top = "100px";
        }
      };

      //回到顶部
      var btn = document.querySelector("button");
      var num = document.documentElement.scrollTop;
      //   console.log(num);
      btn.onclick = function () {
        var timer = setInterval(function () {
          //   console.log(111);
          document.documentElement.scrollTop -= 20;
          if (document.documentElement.scrollTop <= 0) {
            clearInterval(timer);
          }
        }, 10);
      };
    </script>
  </body>
</html>
